package com.hnucm.cooklife.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Context;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.SparseArray;
import android.view.View;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.hnucm.cooklife.R;
//import com.hnucm.cooklife.bean.home.Dish;
import com.hnucm.cooklife.bean.base.Event;
import com.hnucm.cooklife.custom.loading.MyLoading;
import com.hnucm.cooklife.ui.fragment.CollectFragment;
import com.hnucm.cooklife.ui.fragment.HomeFragment;
import com.hnucm.cooklife.ui.fragment.MeFragment;
import com.hnucm.cooklife.ui.fragment.MyFragment;
import com.hnucm.cooklife.ui.fragment.StoreFragment;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private static final int INDEX_HOMEPAGE = 0;
    private static final int INDEX_STORE = 1;
    private static final int INDEX_COLLECT = 2;
    private static final int INDEX_ME = 3;

    private SparseArray<Fragment> mFragmentSparseArray = new SparseArray<>();

    private Fragment mCurrenFragment;

    private Fragment mLastFragment;

    private int mLastIndex = -1;

    private Context mContext;

    Unbinder mUnbinder;

    @BindView(R.id.navigation_bottom)
    BottomNavigationView mBottomNavigationView;

    @BindView(R.id.loading_view)
    MyLoading mLoadingView;

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        //recreate时保存当前页面位置
        outState.putInt("index",mLastIndex);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        //恢复recreate前的页面
        mLastIndex = savedInstanceState.getInt("index");
        switchFragment(mLastIndex);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //解决Fragment需要一个构造函数的问题
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        mContext = getApplicationContext();
        mUnbinder = ButterKnife.bind(this);
        initBottomNavigation();
        //判断当前是recreate还是新启动
        if(savedInstanceState == null){
            switchFragment(INDEX_HOMEPAGE);
        }
        //设置沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initBottomNavigation() {
        mBottomNavigationView.setOnNavigationItemSelectedListener(
                menuItem ->{
                    switch (menuItem.getItemId()){
                        case R.id.menu_home:
                            switchFragment(INDEX_HOMEPAGE);
                            return true;
                        case R.id.menu_store:
                            switchFragment(INDEX_STORE);
                            return true;
                        case R.id.menu_collect:
                            switchFragment(INDEX_COLLECT);
                            return true;
                        case R.id.menu_me:
                            switchFragment(INDEX_ME);
                            return true;
                        default:
                            return false;
                    }
                }
        );
    }


    private void switchFragment(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //将当前显示的fragment和上一个需要隐藏的frament分别加上tag，并获取出来
        //给fragment加上tag，这样可以通过findFragmentByTag找到存在的fragment
        mCurrenFragment = fragmentManager.findFragmentByTag("fragment" + index);
        mLastFragment = fragmentManager.findFragmentByTag("fragment" + mLastIndex);
        //如果位置不同
        if(index != mLastIndex){
            if(mLastFragment != null){
                transaction.hide(mLastFragment);
            }
            if(mCurrenFragment == null){
                mCurrenFragment = getFragment(index);
                transaction.add(R.id.big_container,mCurrenFragment,"fragment" + index);
            } else {
                transaction.show(mCurrenFragment);
            }
        }

        //如果位置相同或新启动的应用
        if(index == mLastIndex){
            if(mCurrenFragment == null){
                mCurrenFragment = getFragment(index);
                transaction.add(R.id.big_container,mCurrenFragment,"framgent" + index);
            }
        }

        transaction.commit();
        mLastIndex = index;
    }

    private Fragment getFragment(int index){
        Fragment fragment = mFragmentSparseArray.get(index);
        if(fragment == null){
            switch (index){
                case INDEX_HOMEPAGE:
                    fragment = HomeFragment.getInstance();
                    break;
                case INDEX_STORE:
                    fragment = StoreFragment.getInstance();
                    break;
                case INDEX_COLLECT:
                    fragment = CollectFragment.getInstance();
                    break;
                case INDEX_ME:
                    fragment = MeFragment.getInstance();
                    break;
                default:
                    break;
            }
            mFragmentSparseArray.put(index,fragment);
        }
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event){
        if(event.target == Event.TARGET_MAIN){
            if(event.type == Event.TYPE_START_ANIMATION){
                if(NetworkUtils.isConnected()){

                    mLoadingView.setVisibility(View.VISIBLE);
                    mLoadingView.startAnimator();
                }
            } else if(event.type == Event.TYPE_STOP_ANIMATION){
                mLoadingView.stopAnimator();
                mLoadingView.setVisibility(View.GONE);
            }
        }
    }

    //    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
////        request();
//    }

//    @BindView(R.id.recycler)
//    RecyclerView mRecyclerView;
//
//    private Context mContext;
//    private RecomAdapter mRecomAdapter;
//    private List<Dish> mDishList = new ArrayList<>();
//
//
//    @Override
//    protected int getContentViewId() {
//        return R.layout.activity_main;
//    }
//
//    @Override
//    protected void init(Bundle savedInstanceState) {
//        mContext = getApplicationContext();
//        mPresenter.loadDish();
//        initAdapter();
//        mRecyclerView.setNestedScrollingEnabled(false);
//    }
//
//    private void initAdapter() {
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
//        mRecomAdapter = new RecomAdapter(mContext,mDishList);
//        mRecyclerView.setAdapter(mRecomAdapter);
//    }
//
//    @Override
//    protected RecomPresenter createPresenter() {
//        return new RecomPresenter();
//    }
//
//    @Override
//    public void onLoadDish(List<Dish> dishList) {
//        mDishList.addAll(dishList);
//        mRecomAdapter.setDishList(mDishList);
//    }
//
//    @Override
//    public void onRefreshDish(List<Dish> dishList) {
//        mDishList.clear();
//        mDishList.addAll(0,dishList);
//        mRecomAdapter.setDishList(mDishList);
//    }
//
//    @Override
//    public void onLoading() {
//
//    }
//
//    @Override
//    public void onLoadingFailed() {
//        ToastUtils.showShort("加载失败");
//    }
//
//    @Override
//    public void onLoadSuccess() {
//
//    }

//    public void request(){
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://10.135.61.117:8080/")//把localhost换成ipv4地址（无线局域网适配器）
//                .addConverterFactory(GsonConverterFactory.create())
//                .build();
//        PostRequest request = retrofit.create(PostRequest.class);
//        //对发送请求进行封装
//        Call<Dish> call = request.getCall();
//        //发送网络请求，异步
//        call.enqueue(new Callback<Dish>() {
//            @Override
//            public void onResponse(Call<Dish> call, Response<Dish> response) {
//                System.out.println(response.body().getData());
//                Log.d(TAG, String.valueOf(response.body().getData().get(0)));
//            }
//
//            @Override
//            public void onFailure(Call<Dish> call, Throwable t) {
//                System.out.println("请求失败");
//                Log.d(TAG, "onFailure");
//                Log.d(TAG, t.getMessage());
//            }
//        });
//    }
}